#include <stdio.h>
#include <windows.h>

HANDLE hdl_wiimote, hdl_nxt, hdl_com;
int wiimote_connected = 0;
int nxt_connected = 0;

void connect_wiimote(void){
   while(1){
      while(!wiimote_connected){
         Sleep(2000);
         wiimote_connected = 1;
      }
      SuspendThread(GetCurrentThread());
   }
} /* thread_connect_wiimote */

void connect_nxt(void){
   while(1){
      while(!nxt_connected){
         Sleep(3000);
         nxt_connected = 1;
      }
      SuspendThread(GetCurrentThread());
   }
} /* thread_connect_nxt */

void communcation(void){
   int i = 0;
   while(1){
      if(!wiimote_connected)
         ResumeThread(hdl_wiimote);
      else if(!nxt_connected)
         ResumeThread(hdl_nxt);
      else
         printf(".");
      Sleep(500);
   }
} /* thread_connect_nxt */

#define BUFFER_SIZE 16
int main(int argc, char **argv){
   char buffer[BUFFER_SIZE];

   setvbuf(stdout, NULL, _IONBF, 0);

   hdl_wiimote =  CreateThread(0, 0, (LPTHREAD_START_ROUTINE)connect_wiimote, 0, CREATE_SUSPENDED, NULL);
   hdl_nxt =      CreateThread(0, 0, (LPTHREAD_START_ROUTINE)connect_nxt,     0, CREATE_SUSPENDED, NULL);
   hdl_com =      CreateThread(0, 0, (LPTHREAD_START_ROUTINE)communcation,    0, CREATE_SUSPENDED, NULL);

   ResumeThread(hdl_com);
   while(1){
      char c = ' ';
      printf("> ");
      fgets(buffer, BUFFER_SIZE, stdin);
      if(!strcmp(buffer, "w\n"))
         wiimote_connected = !wiimote_connected;
      else if(!strcmp(buffer, "n\n"))
         nxt_connected = !nxt_connected;

      printf("Wiimote: %s\n", (wiimote_connected?"connected":"disconnected"));
      printf("    Nxt: %s\n", (nxt_connected    ?"connected":"disconnected"));

      Sleep(500);
   }

   return 0;
} /* main */
